package cn.tedu.csmall.sso.service.impl;


import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.admin.dto.AdminAddDTO;
import cn.tedu.csmall.commons.pojo.admin.dto.AdminLoginDTO;
import cn.tedu.csmall.commons.pojo.admin.model.Admin;
import cn.tedu.csmall.commons.pojo.admin.model.AdminRole;
import cn.tedu.csmall.commons.pojo.admin.vo.AdminListVO;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.commons.untils.JwtUtils;
import cn.tedu.csmall.sso.mapper.AdminMapper;
import cn.tedu.csmall.sso.mapper.AdminRoleMapper;
import cn.tedu.csmall.sso.service.IAdminService;
import cn.tedu.csmall.sso.utils.AdminUserDetails;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
@Slf4j
public class AdminServiceImpl implements IAdminService {


    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    AdminRoleMapper adminRoleMapper;

    @Override
    @Transactional
    public void addNew(AdminAddDTO adminAddDTO) {
        //参数校验
        if(adminAddDTO.getUsername()==null||adminAddDTO.getUsername()==""
        ||adminAddDTO.getPassword()==null||adminAddDTO.getPassword()==""){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"用户名或密码不能为空");
        }
        //判断用户是否存在
        int count = adminMapper.countByUsername(adminAddDTO.getUsername());
        if (count>0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"用户名已存在");
        }
        //新增 管理员对象  插入数据库
        Admin admin=new Admin();
        BeanUtils.copyProperties(adminAddDTO,admin);
               admin.setLastLoginIp(null);
        //加密
        String encode = passwordEncoder.encode(adminAddDTO.getPassword());
      //设置到admin对象属性中
        admin.setPassword(encode);
        admin.setGmtCreate(LocalDateTime.now());
        admin.setGmtModified(LocalDateTime.now());
        int row = adminMapper.insert(admin);
        if (row==0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"网络波动,添加失败");
        }
        AdminRole adminRole=new AdminRole();
        adminRole.setAdminId(admin.getId());
        adminRole.setRoleId(2L);
        adminRole.setGmtCreate(LocalDateTime.now());
        adminRole.setGmtModified(LocalDateTime.now());
        int num = adminRoleMapper.insert(adminRole);
        if (num==0){
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"网络波动,添加失败");
        }
    }

    @Override
    public List<AdminListVO> list() {
        List<AdminListVO> list = adminMapper.list();
        return list;
    }

    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        log.info("处理登录逻辑");
        UsernamePasswordAuthenticationToken upat =
                new UsernamePasswordAuthenticationToken(
                adminLoginDTO.getUsername(),
                adminLoginDTO.getPassword());
        Authentication loginResult = authenticationManager.authenticate(upat);
        //生成JWT===string
        //尝试获取Principal   return userDetails;
        AdminUserDetails user= (AdminUserDetails)loginResult.getPrincipal();
       //登录成功的用户id
        Long id = user.getId();
        //登录成功的用户名
        String username = user.getUsername();
        //登录成功的用户权限
        Collection<GrantedAuthority> authorities = user.getAuthorities();
        //获取权限列表，集合对象，需要转成JSON格式才能放到JWT中
        String aut = JSON.toJSONString(authorities);

        Map<String,Object> claim = new HashMap();
        claim.put("id",id);
        claim.put("username",username);
        claim.put("authorities",aut);

        String jwt = JwtUtils.generate(claim);
        System.out.println(jwt);
        log.info("登陆成功");
        return jwt;
    }




}
